#pragma comment( lib, "E:/code/lua5_1_3_Win32_vc8_lib/lua5.1.lib" )

#include <windows.h>
#include <httpext.h>
#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

/* tools */
void WriteString (EXTENSION_CONTROL_BLOCK *pECB, LPCTSTR lpsz)
{
	DWORD dwBytesWritten;
	dwBytesWritten = lstrlen (lpsz);
	pECB->WriteClient (pECB->ConnID, (PVOID) lpsz, &dwBytesWritten,0);
}

void set_global (lua_State* L, const char* key, const char* value)
{
	lua_pushstring (L, value);
	lua_setglobal (L, key);
}

/* isapi callback apis */
BOOL WINAPI GetExtensionVersion (HSE_VERSION_INFO * pver )
{
	pver->dwExtensionVersion = MAKELONG( HSE_VERSION_MINOR,
	HSE_VERSION_MAJOR );
	lstrcpy( pver->lpszExtensionDesc,
	"hello2 World ISAPI Server Application." );
	return TRUE;
}

DWORD WINAPI HttpExtensionProc( EXTENSION_CONTROL_BLOCK * pecb )
{
	CHAR    buffer[2048];
	DWORD   buflen=0;
	lua_State *L = NULL;
	int error;

	buflen = sizeof(buffer);
	memset(buffer, 0, buflen);
	pecb->GetServerVariable(pecb->ConnID, "PATH_TRANSLATED", buffer, &buflen);
	buffer[buflen] = '\0';
	if (buflen <= 0) 
		return HSE_STATUS_ERROR;

	L = lua_open ();
	if (!L)
		return HSE_STATUS_ERROR;

	luaL_openlibs(L);
	set_global (L, "PATH", buffer);
	error = luaL_loadfile(L, buffer) || lua_pcall(L, 0, 0, 0);
	if (error) {
		lua_pop(L, 1);  /* pop error message from the stack */
	}
	lua_getglobal (L, "OUTPUT");
	if (lua_isstring(L, -1)) {
		const char *output = lua_tostring(L, -1);
		WriteString (pecb, TEXT(output));
	}	

	return HSE_STATUS_SUCCESS;
}


/* entry */
BOOL WINAPI DllMain(IN HINSTANCE hinstDll, IN DWORD fdwReason,IN LPVOID lpvContext OPTIONAL)
{
	BOOL fReturn = TRUE;
	switch (fdwReason )
	{
		case DLL_PROCESS_ATTACH:
		break;
		case DLL_PROCESS_DETACH:
		break;
		default:
		break;
	}
	return ( fReturn);
}